package com.house365.updown.upload;

import java.util.LinkedList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.house365.core.util.TextUtil;
import com.house365.core.util.db.DataBaseOpenHelper;
import com.house365.core.util.db.DataBaseOpenHelper.DataBaseOpenListener;
import com.house365.core.util.db.DataBaseService;
import com.house365.core.util.db.DataBaseService.DBQuery;

/**
 * @author py
 * @date 2013-5-22
 * @comment
 */
public class UploaderDBService {
	private DataBaseService dbService;
	private static UploaderDBService instance;

	public UploaderDBService(Context context) {
		dbService = new DataBaseService(context, "uploader", 1,
				new DataBaseOpenListener() {

					@Override
					public void onVersionUpgrade(SQLiteDatabase db, int arg1,
							int arg2) {

					}

					@Override
					public String[] getIndexSql() {
						String[] indexsqlArray = {
								"CREATE INDEX [IDX_DFILE_OUTERID] ON [ufile]([outerid]  ASC)",
								"CREATE INDEX [IDX_DFILE_REFERID] ON [ufile]([referId]  ASC)" };
						return indexsqlArray;
					}

					@Override
					public String[] getCreateSql() {
						return new String[]{"CREATE TABLE IF NOT EXISTS ufile (identity integer primary key autoincrement,outerid varchar(100),referId long, remoteFileUri varchar(100),totalSize long, uploadSize long,status int,reason int,"
								+ "localFileUri varchar(100),type int,fileParam varchar(100),extralParam varchar(1000))"};
					}
				});
	}

	public static UploaderDBService getDBService(Context context) {
		if (instance == null)
			instance = new UploaderDBService(context);
		return instance;
	}

	public LinkedList<UFile> getUFiles(int type) {
		return (LinkedList<UFile>) dbService.query(
				"select * from ufile where type = " + type, null,
				new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						LinkedList<UFile> ufiles = new LinkedList<UFile>();
						while (cursor.moveToNext()) {
							UFile ufile = new UFile();
							ufile.readFromCursor(cursor);
							ufiles.add(ufile);
						}
						return ufiles;
					}
				});
	}

	public void saveUFiles(int type, LinkedList<UFile> datas) {
		try {
			DataBaseOpenHelper dbo = dbService.getDbOpenHelper();
			SQLiteDatabase db = dbo.getWritableDatabase();
			db.beginTransaction();
			for (UFile ufile : datas) {
				db.execSQL(
						"insert into ufile(outerid,referId, remoteFileUri,totalSize,status,reason,localFileUri,type,fileParam,extralParam)values(?,?,?,?,?,?,?,?,?,?)",
						new Object[] { TextUtil.getUTF8(ufile.getOuterid()),
								ufile.getReferId(),
								TextUtil.getUTF8(ufile.getRemoteFileUri()),
								ufile.getTotalSize(), ufile.getStatus(),
								ufile.getReason(),
								TextUtil.getUTF8(ufile.getLocalFileUri()), 
								type,TextUtil.getUTF8(ufile.getFileParam()),
								TextUtil.getUTF8(ufile.getExtralParam())});
			}
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void saveUFile(UFile ufile, int type) {
		dbService
				.execute(
						"insert into ufile(outerid,referId, remoteFileUri,totalSize,status,reason,localFileUri,type,fileParam,extralParam)values(?,?,?,?,?,?,?,?,?,?)",
						new Object[] { TextUtil.getUTF8(ufile.getOuterid()),
								ufile.getReferId(),
								TextUtil.getUTF8(ufile.getRemoteFileUri()),
								ufile.getTotalSize(), ufile.getStatus(),
								ufile.getReason(),
								TextUtil.getUTF8(ufile.getLocalFileUri()), type,TextUtil.getUTF8(ufile.getFileParam()),
								TextUtil.getUTF8(ufile.getExtralParam())});
	}

	public void removeUFileByReferId(long referid) {
		dbService.execute("delete from  ufile where referId  =  " + referid
				, new Object[] {});
	}

	public void removeUFileOuterId(String outerid) {
		dbService.execute("delete from  ufile where outerid  =  " + outerid
				, new Object[] {});
	}

	public UFile getUFileByReferId(long referid) {
		return (UFile) dbService.query("select * from ufile where referId = ?",
				new String[] { referid + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						UFile ufile = null;
						if (cursor.moveToNext()) {
							ufile = new UFile();
							ufile.readFromCursor(cursor);
						}
						return ufile;
					}
				});
	}

	public UFile getUFileByOuterId(String outerid) {
		return (UFile) dbService.query("select * from ufile where outerid = ?",
				new String[] { outerid }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						UFile ufile = null;
						if (cursor.moveToNext()) {
							ufile = new UFile();
							ufile.readFromCursor(cursor);
						}
						return ufile;
					}
				});
	}

	public UFile getFirstQueueUFile() {
		return (UFile) dbService.query(
				"select * from ufile where type = ? order by identity ",
				new String[] { Uploader.UPLOAD_STAUTS_QUEUE + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						UFile ufile = null;
						if (cursor.moveToNext()) {
							ufile = new UFile();
							ufile.readFromCursor(cursor);
						}
						return ufile;
					}
				});
	}
	public UFile getUploadingUFile() {
		return (UFile) dbService.query(
				"select * from ufile where type = ? order by identity ",
				new String[] { Uploader.UPLOAD_STAUTS_UPLOADING + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						UFile ufile = null;
						if (cursor.moveToNext()) {
							ufile = new UFile();
							ufile.readFromCursor(cursor);
						}
						return ufile;
					}
				});
	}
	public void moveUploadingToQueue(UFile ufile){
		dbService
		.execute(
				"update  ufile set type = ?,totalSize =0,uploadSize=0 where identity = ?",
				new Object[] { Uploader.UPLOAD_STAUTS_QUEUE,ufile.getIdentity()});
	}
	public void moveQueueToUploading(UFile ufile){
		dbService
		.execute(
				"update  ufile set type = ?,referId=? where identity = ?",
				new Object[] { Uploader.UPLOAD_STAUTS_UPLOADING,ufile.getReferId(),ufile.getIdentity()});
	}
	public void moveUploadingToUploaded(UFile ufile){
		dbService
		.execute(
				"update  ufile set type = ?,totalSize =?,uploadSize=?,status = ?,reason = ?,localFileUri = ? where identity = ?",
				new Object[] { Uploader.UPLOAD_STAUTS_UPLOADED,ufile.getTotalSize(),ufile.getUploadSize(),ufile.getStatus(),ufile.getReason(),TextUtil.getUTF8(ufile.getLocalFileUri()),ufile.getIdentity()});
	}
	public void updateUploadingInfo(UFile ufile){
		dbService
		.execute(
				"update  ufile set totalSize =?,uploadSize=?,status = ?,reason = ? where identity = ?",
				new Object[] { ufile.getTotalSize(),ufile.getUploadSize(),ufile.getStatus(),ufile.getReason(),ufile.getIdentity()});
	}
	public void clearUndone(){
		dbService
		.execute("delete from ufile where type != ?",new Object[]{Uploader.UPLOAD_STAUTS_UPLOADED});
	}
	public void clear(){
		dbService
		.execute("delete from ufile",new Object[]{});
	}
}
